package com.yfp.common.core.utils.uuid;

/**
 * @PROJECT_NAME: ydyfp
 * @DESCRIPTION:
 * @USER: xiaohuya
 * @DATE: 2023/12/7 18:11
 */


// Implementing the Snowflake algorithm to generate 32-bit unique IDs
public class Snowflake {
    private static final long START_TIMESTAMP = 1577808000000L; // January 1, 2020
    private static final long SEQUENCE_BIT = 12L;
    private static final long WORKER_BIT = 5L;
    private static final long MAX_WORKER_ID = -1L ^ (-1L << WORKER_BIT);
    private static final long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BIT);
    private long workerId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public Snowflake(long workerId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID can't be greater than " + MAX_WORKER_ID + " or less than 0");
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate ID for " + (lastTimestamp - timestamp) + " milliseconds");
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        return ((timestamp - START_TIMESTAMP) << (WORKER_BIT + SEQUENCE_BIT)) | (workerId << SEQUENCE_BIT) | sequence;
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }

}
